package hlhj.fhp.supreme.activitys

import android.annotation.SuppressLint
import android.content.Intent
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.os.Handler
import android.os.Message
import android.util.Log
import android.view.View
import com.alipay.sdk.app.PayTask
import com.google.gson.Gson
import com.lzy.okgo.OkGo
import com.lzy.okgo.model.Response
import com.tencent.mm.opensdk.modelpay.PayReq
import com.tencent.mm.opensdk.openapi.IWXAPI
import com.tencent.mm.opensdk.openapi.WXAPIFactory
import fhp.hlhj.giantfold.utils.LogUtil
import hlhj.fhp.supreme.BaseAty
import hlhj.fhp.supreme.ClassPayEvent
import hlhj.fhp.supreme.Contents
import hlhj.fhp.supreme.R
import hlhj.fhp.supreme.javabean.*
import hlhj.fhp.supreme.network.Urls
import hlhj.fhp.supreme.utils.JsonCallBack
import hlhj.fhp.supreme.utils.MyUtils
import hlhj.fhp.supreme.utils.OrderInfoUtil2_0
import kotlinx.android.synthetic.main.activity_pay_aty.*
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

class PayAty : BaseAty() {
    private var et =0;
    private var payType=2
    private val SDK_PAY_FLAG = 2
    private lateinit var money:String
    private var shareUrl=""
    private var api: IWXAPI? = null
    private val halder= @SuppressLint("HandlerLeak")
    object :Handler(){
        override fun handleMessage(msg: Message?) {
            super.handleMessage(msg)
            val result = msg!!.obj as Map<String, String>
            val status = result["resultStatus"]
            val ss = result["sub_msg"]
            LogUtil.logi("结果----$ss")
            if (msg!!.arg1==100){
                if (status=="9000"){
                    MyUtils.toast("支付成功")
                    val intent = Intent(this@PayAty, JiePanPayResultAty::class.java)
                    intent.putExtra("type","1")
                    intent.putExtra("url",shareUrl)
                    startActivity(intent)
                    this@PayAty.setResult(-1)
                    finish()
                }
            }else{
                if (status == "9000") {
                    MyUtils.toast("支付成功")
                    setResult(-1)
                    val intent = Intent(this@PayAty, PaySuccessAty::class.java)
                    intent.putExtra("type","1")
                    startActivity(intent)
                    finish()
//                recreate()
                }else{
                    val intent = Intent(this@PayAty, PaySuccessAty::class.java)
                    intent.putExtra("type","2")
                    startActivity(intent)
                    finish()
                }
            }

        }
    }
    override fun getContentId(): Int {
        return R.layout.activity_pay_aty
    }

    //et 1-读书 2-课堂 3-订单购物车 4-订单立即购买
    override fun initView() {
        EventBus.getDefault().register(this)
        et = intent.getIntExtra("et", 0)
        api = WXAPIFactory.createWXAPI(this, Contents.WXAPPKEY,true)
        api!!.registerApp(Contents.WXAPPKEY)

        if (intent.getStringExtra("type").equals("1")){//0普通商城 1 积分商城 2课堂/读书
            tv1.visibility=View.GONE
            loZfb.visibility=View.GONE
            loWx.visibility=View.GONE
        }else{
            tv1.visibility=View.VISIBLE
            loZfb.visibility=View.VISIBLE
            loWx.visibility=View.VISIBLE
        }

        when(et){
            1->{
                money=intent.getStringExtra("money")
                tvPrice.text="￥${money}"
            }
            2->{
                money=intent.getStringExtra("money")
                tvPrice.text="￥${money}"
            }
            3->{
                money=intent.getStringExtra("money")
//                MyUtils.toast(money+"-"+intent.getStringExtra("type"))
                when(intent.getStringExtra("type")){
                    "0"->{
                        tvPrice.text="${money}"
                    }
                    "1"->{
                        tvPrice.text="${money}"
                    }
                }
            }
            4->{
                money=intent.getStringExtra("money")
//                MyUtils.toast(money+"-"+intent.getStringExtra("type"))
                when(intent.getStringExtra("type")){
                    "0"->{
                        tvPrice.text="${money}"
                    }
                    "1"->{
                        tvPrice.text="${money}"
                    }
                }
            }
            5->{
                money=intent.getStringExtra("money")
//                MyUtils.toast(money+"-"+intent.getStringExtra("type"))
                when(intent.getStringExtra("type")){
                    "0"->{
                        tvPrice.text="￥${money}"
                    }
                    "1"->{
                        tvPrice.text="￥${money}"
                    }
                    "2"->{
                        tvPrice.text="￥${money}"
                    }
                }
            }
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        EventBus.getDefault().unregister(this)
    }
    override fun initListener() {
        btExit.setOnClickListener {
            finish()
        }
        loZfb.setOnClickListener {
            payType=2
            cbZfb.isChecked=true
            cbWX.isChecked=false
        }

        loWx.setOnClickListener {
            payType=1
            cbZfb.isChecked=false
            cbWX.isChecked=true
        }

        btCommit.setOnClickListener {
            when(et){
                3->{
                    when(payType){
                        1->{
                            if (intent.getStringExtra("type").equals("0")){

                                OkGo.post<WxPayBean>(Urls.BaseUrl+Urls.CART_ORDER)
                                        .params("ids",intent.getStringExtra("ids"))
                                        .params("type",intent.getStringExtra("type"))
                                        .params("aid",intent.getStringExtra("aid"))
                                        .params("pay_type",1)
                                        .execute(object :JsonCallBack<WxPayBean>(this){
                                            override fun onSuccess(response: Response<WxPayBean>?) {
                                                val bean = response?.body()
                                                if (bean?.code==1){
                                                    runOnUiThread {
                                                        val data = bean?.data
                                                        MyUtils.toast("提交订单成功")
                                                        val req = PayReq()
                                                        req.appId=data.appid
                                                        req.partnerId = data.partnerid
                                                        req.prepayId = data.prepayid
                                                        req.nonceStr = data.noncestr
                                                        req.timeStamp = data.timestamp.toString()
                                                        req.packageValue = data.packageX
                                                        req.sign = data.sign
                                                        req.extData="购物车支付"
                                                        api!!.sendReq(req)
                                                        finish()
                                                    }
//                                setResult(-1)
//                                finish()

                                                }else{
                                                    MyUtils.toast(bean?.msg)
                                                }
                                            }
                                        })
                            }
                            else{
                                OkGo.post<WxPayBean>(Urls.BaseUrl+Urls.CART_ORDER)
                                        .params("ids",intent.getStringExtra("ids"))
                                        .params("type",intent.getStringExtra("type"))
                                        .params("aid",intent.getStringExtra("aid"))
                                        .params("pay_type",1)
                                        .execute(object :JsonCallBack<WxPayBean>(this){
                                            override fun onSuccess(response: Response<WxPayBean>?) {
                                                val bean = response?.body()
                                                if (bean?.code==1){
                                                    val data = bean?.data
                                                    MyUtils.toast("提交订单成功")

                                                    /*    setResult(-1)
                                                        finish()*/

                                                }else{
                                                    MyUtils.toast(bean?.msg)
                                                }
                                            }
                                        })
                            }
                        }
                        2->{
                            if (intent.getStringExtra("type").equals("0")){
                                OkGo.post<AliPayBean>(Urls.BaseUrl+Urls.CART_ORDER)
                                        .params("ids",intent.getStringExtra("ids"))
                                        .params("type",intent.getStringExtra("type"))
                                        .params("aid",intent.getStringExtra("aid"))
                                        .params("pay_type",2)
                                        .execute(object :JsonCallBack<AliPayBean>(this){
                                            override fun onSuccess(response: Response<AliPayBean>?) {
                                                val body = response?.body()
                                                if (body?.code==1){
                                                    val s = body?.data.pay_data
                                                    LogUtil.logi(s)
                                                    val runnable = Runnable {
                                                        val alipay = PayTask(this@PayAty)
                                                        val result = alipay.payV2(s, true)
                                                        val msg = Message()
                                                        msg.what = SDK_PAY_FLAG
                                                        msg.obj = result
                                                        halder.sendMessage(msg)
                                                    }
                                                    val t = Thread(runnable)
                                                    t.start()
                                                }
                                            }
                                        })
                            }else{
                                OkGo.post<WxPayBean>(Urls.BaseUrl+Urls.CART_ORDER)
                                        .params("ids",intent.getStringExtra("ids"))
                                        .params("type",intent.getStringExtra("type"))
                                        .params("aid",intent.getStringExtra("aid"))
                                        .params("pay_type",1)
                                        .execute(object :JsonCallBack<WxPayBean>(this){
                                            override fun onSuccess(response: Response<WxPayBean>?) {
                                                val bean = response?.body()
                                                if (bean?.code==1){
                                                    val data = bean?.data
                                                    setResult(-1)
                                                    finish()
                                                    MyUtils.toast("提交订单成功")
                                                }else{
                                                    MyUtils.toast(bean?.msg)
                                                }
                                            }
                                        })
                            }
                        }
                    }
                }//购物车下单
                4->{
                    when(payType){
                        1->{
                            if (intent.getStringExtra("type").equals("0")){
                                OkGo.post<WxPayBean>(Urls.BaseUrl+Urls.QUICK_ORDER)
                                        .params("goods_id",intent.getStringExtra("id"))
                                        .params("number",1)
                                        .params("aid",intent.getStringExtra("aid"))
                                        .params("pay_type",1)
                                        .execute(object :JsonCallBack<WxPayBean>(this){
                                            override fun onSuccess(response: Response<WxPayBean>?) {
                                                val bean = response?.body()
                                                if (bean?.code==1){
                                                    runOnUiThread {
                                                        val data = bean?.data
                                                        val req = PayReq()
                                                        req.appId=data.appid
                                                        req.partnerId = data.partnerid
                                                        req.prepayId = data.prepayid
                                                        req.nonceStr = data.noncestr
                                                        req.timeStamp = data.timestamp.toString()
                                                        req.packageValue = data.packageX
                                                        req.sign = data.sign
                                                        api!!.sendReq(req)
                                                        finish()
                                                    }
//                                setResult(-1)
//                                finish()
                                                }else{
                                                    MyUtils.toast(bean?.msg)
                                                }
                                            }
                                        })
                            }else{
                                OkGo.post<BaseBean>(Urls.BaseUrl+Urls.QUICK_ORDER)
                                        .params("goods_id",intent.getStringExtra("id"))
                                        .params("number",1)
                                        .params("aid",intent.getStringExtra("aid"))
                                        .execute(object :JsonCallBack<BaseBean>(this@PayAty){
                                            override fun onSuccess(response: Response<BaseBean>?) {
                                                val bean = response?.body()
                                                if (bean?.code==1){
                                                    MyUtils.toast("购买成功")
                                                    finish()
                                                }else{
                                                    MyUtils.toast(bean?.msg)
                                                }
                                            }
                                        })
                            }
                        }
                        2->{
                            if (intent.getStringExtra("type").equals("0")) {
                                OkGo.get<AliPayBean>(Urls.BaseUrl+Urls.QUICK_ORDER)
                                        .params("goods_id",intent.getStringExtra("id"))
                                        .params("number",1)
                                        .params("aid",intent.getStringExtra("aid"))
                                        .params("pay_type",2)
                                        .execute(object :JsonCallBack<AliPayBean>(this@PayAty){
                                            override fun onSuccess(response: Response<AliPayBean>?) {
                                                val bean = response?.body()
                                                if (bean?.code==1){
                                                    val s = bean?.data.pay_data
                                                    LogUtil.logi(s)
                                                    val runnable = Runnable {
                                                        val alipay = PayTask(this@PayAty)
                                                        val result = alipay.payV2(s, true)
                                                        val msg = Message()
                                                        msg.what = SDK_PAY_FLAG
                                                        msg.obj = result
                                                        halder.sendMessage(msg)
                                                    }
                                                    val t = Thread(runnable)
                                                    t.start()

                                                }
                                            }
                                        })
                            }
                            else{
                                OkGo.post<BaseBean>(Urls.BaseUrl+Urls.QUICK_ORDER)
                                        .params("goods_id",intent.getStringExtra("id"))
                                        .params("number",1)
                                        .params("aid",intent.getStringExtra("aid"))
                                        .execute(object :JsonCallBack<BaseBean>(this@PayAty){
                                            override fun onSuccess(response: Response<BaseBean>?) {
                                                val bean = response?.body()
                                                if (bean?.code==1){
                                                    MyUtils.toast("购买成功")
                                                    finish()
                                                }else{
                                                    MyUtils.toast(bean?.msg)
                                                }
                                            }
                                        })
                            }
                        }
                    }
                }//快速下单
                2->{
                    when(payType){
                        1->{
                            OkGo.post<WxPayBean>(Urls.BaseUrl+Urls.CLASS_PAY)
                                    .params("ids",intent.getStringExtra("ids"))
                                    .params("pay_type",payType)
                                    .execute(object :JsonCallBack<WxPayBean>(this){
                                        override fun onSuccess(response: Response<WxPayBean>?) {
                                            val bean = response?.body()
                                            if (bean?.code==1){
                                                val data = bean?.data
                                                val req = PayReq()
                                                req.appId=data.appid
                                                req.partnerId = data.partnerid
                                                req.prepayId = data.prepayid
                                                req.nonceStr = data.noncestr
                                                req.timeStamp = data.timestamp.toString()
                                                req.packageValue = data.packageX
                                                req.sign = data.sign
                                                req.extData="课堂支付"
                                                api!!.sendReq(req)
                                            }
                                        }
                                    })
                        }
                        2->{
                            OkGo.post<AliPayBean>(Urls.BaseUrl+Urls.CLASS_PAY)
                                    .params("ids",intent.getStringExtra("ids"))
                                    .params("pay_type",payType)
                                    .execute(object :JsonCallBack<AliPayBean>(this){
                                        override fun onSuccess(response: Response<AliPayBean>?) {
                                            val bean = response?.body()
                                            if (bean?.code==1){
                                                val s = bean?.data.pay_data
                                                LogUtil.logi(s)
                                                val runnable = Runnable {
                                                    val alipay = PayTask(this@PayAty)
                                                    val result = alipay.payV2(s, true)
                                                    val msg = Message()
                                                    msg.what = SDK_PAY_FLAG
                                                    msg.obj = result
                                                    halder.sendMessage(msg)
                                                }
                                                val t = Thread(runnable)
                                                t.start()
                                            }
                                        }
                                    })
                        }
                    }

                }//课堂
                1->{
                    when(payType){
                        1->{//微信
                            OkGo.post<WxPayBean>(Urls.BaseUrl+Urls.BUYBOOK)
                                    .params("id",intent.getIntExtra("id",0))
                                    .params("pay_type",payType)
                                    .execute(object :JsonCallBack<WxPayBean>(this@PayAty){
                                        override fun onSuccess(response: Response<WxPayBean>?) {
                                            val wxPayBean = response?.body()
                                            if (wxPayBean!!.code==1){
                                                val data = wxPayBean?.data
                                                val req = PayReq()
                                                req.appId=data.appid
                                                req.partnerId = data.partnerid
                                                req.prepayId = data.prepayid
                                                req.nonceStr = data.noncestr
                                                req.timeStamp = data.timestamp.toString()
                                                req.packageValue = data.packageX
                                                req.sign = data.sign
                                                req.extData="书籍支付"
                                                api!!.sendReq(req)
                                            }
                                        }
                                    })
                        }
                        2->{
                            OkGo.post<AliPayBean>(Urls.BaseUrl+Urls.BUYBOOK)
                                    .params("id",intent.getIntExtra("id",0))
                                    .params("pay_type",payType)
                                    .execute(object :JsonCallBack<AliPayBean>(this@PayAty){
                                        override fun onSuccess(response: Response<AliPayBean>?) {
                                            val aliPayBean = response?.body()
                                            if (aliPayBean!!.code==1){
                                                val s = aliPayBean.data.pay_data
                                                LogUtil.logi(s)
                                                val runnable = Runnable {
                                                    val alipay = PayTask(this@PayAty)
                                                    val result = alipay.payV2(s, true)
                                                    val msg = Message()
                                                    msg.what = SDK_PAY_FLAG
                                                    msg.obj = result
                                                    halder.sendMessage(msg)
                                                }
                                                val t = Thread(runnable)
                                                t.start()
                                            }
                                        }
                                    })
                        }
                    }
                }//读书
                5->{//解盘
                    when(payType){
                        1->{
                            OkGo.post<WxPayBean>(Urls.BaseUrl+Urls.PAY_JIEPAN)
                                    .params("pay_type",payType)
                                    .params("type",if (intent.getIntExtra("pp",1)==1)0 else 1)
                                    .params("people",intent.getIntExtra("pp",5))
                                    .execute(object :JsonCallBack<WxPayBean>(this@PayAty){
                                        override fun onSuccess(response: Response<WxPayBean>?) {
                                            val wxPayBean = response?.body()
                                            if (wxPayBean!!.code==1){
                                                if (wxPayBean.data.share_url!=null){
                                                    shareUrl=wxPayBean.data.share_url
                                                }
                                                val data = wxPayBean?.data
                                                val req = PayReq()
                                                req.appId=data.appid
                                                req.partnerId = data.partnerid
                                                req.prepayId = data.prepayid
                                                req.nonceStr = data.noncestr
                                                req.timeStamp = data.timestamp.toString()
                                                req.packageValue = data.packageX
                                                req.sign = data.sign
                                                LogUtil.log("-----------------${intent.getIntExtra("pp",1)}")
                                                if (intent.getIntExtra("pp",1)==1){
                                                    req.extData="解盘单人"
                                                }else{
                                                    req.extData="解盘团购"
                                                }
                                                api!!.sendReq(req)
                                            }
                                        }
                                    })
                        }
                        2->{
                            OkGo.post<AliPayBean>(Urls.BaseUrl+Urls.PAY_JIEPAN)
                                    .params("pay_type",payType)
                                    .params("type",if (intent.getIntExtra("pp",1)==1)0 else 1)
                                    .params("people",intent.getIntExtra("pp",5))
                                    .execute(object :JsonCallBack<AliPayBean>(this@PayAty){
                                        override fun onSuccess(response: Response<AliPayBean>?) {
                                            val aliPayBean = response?.body()
                                            if (aliPayBean!!.code==1){
                                                val s = aliPayBean.data.pay_data
                                                LogUtil.logi(s)
                                                if (aliPayBean.data.share_url!=null){
                                                    shareUrl=aliPayBean.data.share_url
                                                }
                                                val runnable = Runnable {
                                                    val alipay = PayTask(this@PayAty)
                                                    val result = alipay.payV2(s, true)
                                                    val msg = Message()
                                                    msg.what = SDK_PAY_FLAG
                                                    msg.obj = result
                                                    if (shareUrl.equals("")){
                                                        msg.arg1=200
                                                    }else{
                                                        msg.arg1=100
                                                    }
                                                    halder.sendMessage(msg)
                                                }
                                                val t = Thread(runnable)
                                                t.start()
                                            }
                                        }
                                    })
                        }
                    }
                }//解盘
                else->{

                }

            }

        }
    }

    @Subscribe(threadMode = ThreadMode.POSTING)
    public fun handlePay(event:ClassPayEvent){
        this@PayAty.setResult(-1)
        val intent = Intent(this@PayAty, PaySuccessAty::class.java)
        intent.putExtra("type","1")
        startActivity(intent)
        finish()
    }
    @Subscribe(threadMode = ThreadMode.POSTING)
    public fun handReadPay(event:ReadPayEvent){
        this@PayAty.setResult(-1)
        val intent = Intent(this@PayAty, PaySuccessAty::class.java)
        intent.putExtra("type","1")
        startActivity(intent)
        finish()
    }
    @Subscribe(threadMode = ThreadMode.POSTING)
    public fun handJiePanPay(event:JiePanPayEvent){
        this@PayAty.setResult(-1)
        val intent = Intent(this@PayAty, PaySuccessAty::class.java)
        intent.putExtra("type","1")
        startActivity(intent)
        finish()
    }
    @Subscribe(threadMode = ThreadMode.POSTING)
    public fun handJiePanPay(event:JiePanDanRenEvent){

        val intent = Intent(this@PayAty, PaySuccessAty::class.java)
        intent.putExtra("type","1")
//        intent.putExtra("url",shareUrl)
        startActivity(intent)
        this@PayAty.setResult(-1)
        finish()
    }
    @Subscribe(threadMode = ThreadMode.POSTING)
    public fun handJiePanPay(event:JiePanTuanGouEvent){

        LogUtil.log("进入团购回调1")
        val intent = Intent(this@PayAty, JiePanPayResultAty::class.java)
        intent.putExtra("type","1")
        intent.putExtra("url",shareUrl)
        startActivity(intent)
        this@PayAty.setResult(-1)
        finish()
    }
    @Subscribe(threadMode = ThreadMode.POSTING)
    public fun handPayFail(event: PayfailEvent){
        this@PayAty.setResult(-1)
        val intent = Intent(this@PayAty, PaySuccessAty::class.java)
        intent.putExtra("type","2")
        startActivity(intent)
        finish()
    }

}
